package com.woniuxy.qimengauth.controller;

import com.woniuxy.qimengauth.bean.UserBean;
import com.woniuxy.qimengauth.service.IUserService;
import com.woniuxy.qimengcommons.bean.ReturnMsg;
import com.woniuxy.qimengcommons.enums.RespStatus;
import com.woniuxy.qimengcommons.util.JwtUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/sys")
@RestController
public class SystemController {
    @Resource
    private IUserService userServiceImpl;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ValueOperations valueOperations;


    @PostMapping(value="/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public ReturnMsg login(String loginName, String password) {
        ReturnMsg returnMsg = new ReturnMsg(RespStatus.LOGIN_SUCCESS);
        try {
            System.out.println(loginName);
            System.out.println(password);

            //由于数据库中存储的是，加密密码，所以此处需要先加密
            String pwd = new SimpleHash("MD5", password, loginName, 1024).toString();
            UserBean userBean = userServiceImpl.login(loginName,pwd);

            if(userBean != null){
                Map<String,Object> claims = new HashMap<>();
                //存放私有的载荷信息
                claims.put("userName",userBean.getUserName());
                String token = jwtUtil.createToken(claims);
                //将Token令牌以及自定义的签名，存储到Redis中
                valueOperations.set(token,claims);
                returnMsg.setToken(token);

                //将查询出来的用户信息，传递给前端
                returnMsg.setData(userBean);
            }else{
                returnMsg.setStatus(RespStatus.ACCOUNT_FAILED);
            }
        } catch (Exception e) {
            returnMsg.setStatus(RespStatus.LOGIN_FAILED);
        }
        return returnMsg;
    }
}
